#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define dprintf(fmt, ...) printf("%s:%d " fmt, __FILE__, __LINE__, ##__VA_ARGS__)

extern void fdisk_list(char* hd_img);

int sub_read_file(char* full_fn, char** out_buf, int* out_len) {
    FILE* f = fopen(full_fn, "rb");
    char* buf = 0;
    long buf_len = 0;

    if(!f) {
        dprintf("open %s failed!\n", full_fn);
        return -1;
    }
    fseek(f, 0, SEEK_END);
    buf_len = ftell(f);
    fseek(f, 0, SEEK_SET);
    buf = (char*)malloc(buf_len);
    if(1 != fread(buf, buf_len, 1, f)) {
        dprintf("read %s failed!\n", full_fn);
        free(buf);
        fclose(f);
        return -1;
    }
    fclose(f);
    *out_buf = buf;
    *out_len = buf_len;

    return 0;
}
int sub_write_file(char* full_fn, char* buf, int len) {
    FILE* f = fopen(full_fn, "w"); //Truncate file to zero length or create text file for writing

    if(!f) {
        dprintf("open %s failed!\n", full_fn);
        return -1;
    }
    if(1 != fwrite(buf, len, 1, f)) {
        dprintf("write %s failed!\n", full_fn);
        fclose(f);
        return -1;
    }
    fclose(f);

    return 0;
}

int sub_write_file_ex(char* write_to_fn, int write_to_pos, char* buf, int len) {
    char* rbuf = 0;
    int rbuf_len = 0;

    if (0 != sub_read_file(write_to_fn, &rbuf, &rbuf_len)) {
        return -1;
    }
    memcpy(&rbuf[write_to_pos], buf, len);
    if (0 != sub_write_file(write_to_fn, rbuf, rbuf_len)) {
        return -1;
    }
    free(rbuf);
    return 0;
}

int add_sector(char* from_fn, char* to_fn, int sector_idx) {
    char* buf_from = 0;
    int buf_from_len = 0;

    if(0 != sub_read_file(from_fn, &buf_from, &buf_from_len)) {
        return -1;
    }
    if(0 != sub_write_file_ex(to_fn, sector_idx * 512, buf_from, buf_from_len)) {
        return -1;
    }
    free(buf_from);
    return 0;
}

int test_sect(char* fn) {
    char data[512] = {0};
    char* img = 0;
    int len = 0;
    int i = 0;
    int j = 0;


    sub_read_file(fn, &img, &len);

    for(i = 1; i < 2880; ++i) { //start@sect1
        ((short*)data)[0] = i;
        data[510] = 0xbb;
        data[511] = 0x66;
        memcpy(&img[i * 512], data, 512);
    }

    sub_write_file(fn, img, len);
    free(img);

}

void show_help() {
    printf("usage:\n");
    printf("  ...\n");
}

int main(int argc, char* argv[]) {
    if(0 == strcmp(argv[1],"-add_sect")) {
        if(argc != 5) {
            show_help();
        }
        int sector_idx = atoi(argv[4]);
        return add_sector(argv[2], argv[3], sector_idx);
    } else if(0 == strcmp(argv[1], "-t")) {
        test_sect(argv[2]);
    } else if(0 == strcmp(argv[1], "-fdl")) {
        fdisk_list(argv[2]);
    }
    return 0;
}
